package cc.wanforme.st.server.interceptor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.ObjectUtils;

/** 代码摘取自 {@link org.springframework.web.cors.CorsConfiguration.OriginPattern} <br>
 * 此代码是 spring 跨域检查 origin 时使用的，为保持一致性，使用相同的方法进行判断。（原代码不能直接使用）  <br>
 * Contains both the user-declared pattern (e.g. "https://*.domain.com") and
 * the regex {@link Pattern} derived from it.
 * @see org.springframework.web.cors.CorsConfiguration 
 */
public class ReferedPattern {
	/** Wildcard representing <em>all</em> origins, methods, or headers. */
	public static final String ALL = "*";
	
	private static final Pattern PORTS_PATTERN = Pattern.compile("(.*):\\[(\\*|\\d+(,\\d+)*)]");

	private final String declaredPattern;

	private final Pattern pattern;

	public ReferedPattern(String declaredPattern) {
		this.declaredPattern = declaredPattern;
		this.pattern = initPattern(declaredPattern);
	}

	private static Pattern initPattern(String patternValue) {
		String portList = null;
		Matcher matcher = PORTS_PATTERN.matcher(patternValue);
		if (matcher.matches()) {
			patternValue = matcher.group(1);
			portList = matcher.group(2);
		}

		patternValue = "\\Q" + patternValue + "\\E";
		patternValue = patternValue.replace("*", "\\E.*\\Q");

		if (portList != null) {
			patternValue += (portList.equals(ALL) ? "(:\\d+)?" : ":(" + portList.replace(',', '|') + ")");
		}

		return Pattern.compile(patternValue);
	}

	public String getDeclaredPattern() {
		return this.declaredPattern;
	}

	public Pattern getPattern() {
		return this.pattern;
	}

	@Override
	public boolean equals(Object other) {
		if (this == other) {
			return true;
		}
		if (other == null || !getClass().equals(other.getClass())) {
			return false;
		}
		return ObjectUtils.nullSafeEquals(
				this.declaredPattern, ((ReferedPattern) other).declaredPattern);
	}

	@Override
	public int hashCode() {
		return this.declaredPattern.hashCode();
	}

	@Override
	public String toString() {
		return this.declaredPattern;
	}
}
